<?php

namespace app\api\controller;

use app\admin\model\Tickets;
use app\api\model\Cdklog;
use app\api\model\Commodity;
use app\api\model\Message;
use app\api\model\Paylog;
use app\api\model\Users;
use think\Request;

class Shop extends Authorization
{
    public function getCommodityList(Request $request){
        $paylog = new Paylog();
        $cdkcount = (new Tickets())->where(['type'=>1,'use_id'=>0])->count();
        (new Commodity())->where('id',2)->update(['residue'=>$cdkcount]);
        $list = (new Commodity())->where('status','上架')->order('id asc')->select();
        $arr = [];
        foreach ($list as $k=>$v){
            if($v['limit'] == 0){
                $v['close'] = false;
            }else{
                $s = $paylog->where(['users_id'=>$request->user->user_id,'commodity_id'=>$v['id']])->whereTime('create_time','month')->count();
                if($s <= $v['limit']){
                    $v['close'] = false;
                }else $v['close'] = true;
            }
            $arr[] = $v;
        }
        return $this->success('ok',['data'=>$arr,'count'=>count($list)]);
    }
    public function submit(Request $request){
        if($request->isPost()){
            $params = $request->param();

            $sql = $this->doPay($request->user,$params);
            if($sql['status'] == false) return $this->error($sql['msg']);

            return $this->success('购买成功！');
        }
    }
    private function doPay($users,$params){
        $userModel = new Users();
        $paylog = new Paylog();
        $tickets = new Tickets();
        $user = $userModel->where('id',$users->user_id)->find();
        $shop = (new Commodity())->where('id',$params['check'])->find();
        if ((int)$shop['residue'] <= 0) return ['status'=>false,'msg'=>$shop['name'].' 已售完！'];
//        if ((int)$params['check'] == 2 and (new Tickets())->where(['type'=>1,'use_id'=>0])->count() <= 0) return ['status'=>false,'msg'=>$shop['name'].' 已售完！'];
        if((int)$shop['limit'] !== 0){
            $count = $paylog->where(['users_id'=>$users->user_id,'commodity_id'=>$params['check']])->whereTime('create_time','month')->count();
            if($count >= $shop['limit']) return ['status'=>false,'msg'=>$shop['name'].' 已达到本月限购数量'];
        }
        $currentMonthIntegral = (new Paylog())->where('users_id',$users->user_id)->whereTime('create_time','month')->sum('value');
        if($currentMonthIntegral >= (int)$this->settings['user_month_integral_limit']) return ['status'=>false,'msg'=>'已达到本月可使用积分上限'];
        if(($currentMonthIntegral + (int)$shop['scale']) >= (int)$this->settings['user_month_integral_limit']) return ['status'=>false,'msg'=>'购买失败！本月可用积分不足，仅剩：'.((int)$this->settings['user_month_integral_limit']-$currentMonthIntegral)];
        if((int)$user['integral'] >= (int)$shop['scale']){
//            扣除积分并分发商品,减少商品
            if((int)$shop['type'] == 0){
                $pay_id = $paylog->insertGetId([
                    'users_id'      =>  $users->user_id,
                    'commodity_id'  =>  $shop['id'],
                    'value'         => $shop['scale'],
                    'status'        => 0,
                    'create_time'   => time()
                ]);
                $msg = '[ ME系统消息 ]: '.$users->data->nickname."\n";
                $msg .= "兑换订单：".$pay_id."\n";
                $msg .= "已成功提交！请联系管理员游戏内PY交易。";
                (new Message())->send_qq($users->user_id,$users->data->qq,$msg);
            }else{
                $card = $tickets->where(['type'=>1,'use_id'=>0])->order('id desc')->find();
                $tickets->where('id',$card['id'])->update(['use_id'=>$users->user_id]);
                $pay_id = $paylog->insertGetId([
                    'users_id'      =>  $users->user_id,
                    'commodity_id'  =>  $shop['id'],
                    'value'         => $shop['scale'],
                    'status'        => 1,
                    'create_time'   => time()
                ]);
                 (new Cdklog())->insertGetId([
                    'users_id'          => $users->user_id,
                    'tickets_id'        => $card['id'],
                    'shop_id'           => $pay_id,
                    'content'           => $card['content'],
                     'create_time'   => time()
                ]);
                $msg = '[ ME系统消息 ]: '.$users->data->nickname."\n";
                $msg .= "兑换订单：".$pay_id."\n";
                $msg .= "saibo CDK : ".$card['content']."\n";

                (new Message())->send_qq($users->user_id,$users->data->qq,$msg);
            }
            (new Commodity())->where('id',$params['check'])->update(['residue'=>(int)$shop['residue'] - 1]);
            $userModel->where('id',$users->user_id)->update(['integral'=>bcsub($user['integral'],$shop['scale'],3)]);
            return ['status'=>true,'msg'=>'ok'];
        }else{
            return ['status'=>false,'msg'=>'您的积分不足兑换此商品'];
        }
    }
}